package com.javaweb.bookstore.servlet;

import com.javaweb.bookstore.component.IUserManager;
import com.javaweb.bookstore.component.JdbcUserManager;
import com.javaweb.bookstore.entity.ResponseEntity;
import com.javaweb.bookstore.entity.UserInfo;
import com.javaweb.bookstore.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    IUserManager userManager = JdbcUserManager.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        UserInfo user = userManager.getUserByNameAndPassword(userName, password);

        if(user != null ) {
            HttpSession session = req.getSession(true);
            UserInfo ui = new UserInfo();
            ui.setName(userName);
            session.setAttribute("userinfo", ui);
            ResponseEntity re = new ResponseEntity(true, "登录成功！", null);
            String json = Utils.obj2json(re);
            resp.getWriter().println(json);
            return ;
        }
        ResponseEntity re = new ResponseEntity(false, "Login Failed!", null);
        String json = Utils.obj2json(re);
        resp.getWriter().println(json);

    }
}
//1. 有一个叫sessionid的cookie被产生并随同响应交付给了浏览器 2.session对象被保存了(涉及到对象序列化)